﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint.Portal.WebControls;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.Office.Server.Diagnostics;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Portal;
using System.Web.UI.WebControls;
using System.Web;


namespace SharePoint.MySpace
{
    public class CreateMySpace: PersonalAdminPage // SitePage //:CreatePersonalSpace
    {
        public const string MySpaceTemplateProperty = "MySpaceTemplate";

        // Fields
        protected Literal BodyText;
        protected InputFormButtonAtBottom btnCancel;
        protected InputFormButtonAtBottom btnOK;
        private const string c_QueryStringError = "Error";
        private const string c_QueryStringLanguage = "Lang";
        protected InputFormDropDownList ddlLanguages;
        protected ImageLoc ImageProgress;
        protected InputForm InputForm1;
        protected PageLevelError PageLevelError1;
        protected LabelLoc TextProgress;


        public CreateMySpace()
        {
            string t = string.Empty;
        }

        protected override void OnLoad(EventArgs e)
        {
            string str = HttpContext.Current.Request.QueryString[c_QueryStringError];
            if (string.IsNullOrEmpty(str))
            {

                base.OnLoad(e);

                //check if personal site exists and redirect 
                UserProfile userProfile = ProfileLoader.GetProfileLoader().GetUserProfile();
                //string strMySiteUrl = (string)userProfile[PropertyConstants.PersonalSpace].Value;
                SPSite site = userProfile.PersonalSite;

                if (site != null && site.RootWeb != null)
                {
                    //Redirect to the Personal Site
                    Context.Response.Redirect(site.RootWeb.Url);
                }
                else
                {
                    //create new MySite
                    CreateSiteWithinFrame(null);
                }
            }
            else //we got an error
            {
                this.ImageProgress.Visible = false;
                this.TextProgress.Visible = false;
                this.PageLevelError1.ErrorText = str;
                return;
            }
        }

        protected void CreateSiteWithinFrame(string desiredLanguage)
        {
            if (this.Page.IsPostBack)
            {
               // SPUtility.ValidateFormDigest();
                string scriptLiteralToEncode = this.RaiseCallbackEvent(desiredLanguage);
                this.Page.ClientScript.RegisterStartupScript(base.GetType(), "CreateMySiteParentRedirect", "\r\n                    parent.window.clearTimeout(parent.window.timeoutErrorHnd);\r\n                    parent.window.location.href = '" + SPHttpUtility.EcmaScriptStringLiteralEncode(scriptLiteralToEncode) + "';\r\n                ", true);
            }
            else
            {
                this.Page.ClientScript.RegisterStartupScript(base.GetType(), "CreateMySiteRepost", "document.forms[0].submit();", true);
            }
        }

 

 

        public string RaiseCallbackEvent(string eventArg)
        {
            //string str3;
            string message = string.Empty;
            string str2 = string.Empty;
            UserProfile userProfile = null;
            try
            {
                userProfile = ProfileLoader.GetProfileLoader().GetUserProfile();
                str2 = (string)userProfile["AccountName"].Value;
                if (!string.IsNullOrEmpty(eventArg))
                {
                    // userProfile.CreatePersonalSite(int.Parse(eventArg, CultureInfo.InvariantCulture));
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {

                        //TODO: support different cultures
                        CreateMySite(userProfile); //, int.Parse(eventArg, CultureInfo.InvariantCulture));
                    });
                }
                else
                {
                    // userProfile.CreatePersonalSite();
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {

                        CreateMySite(userProfile);
                    });
                }
            }
            catch (Exception exception)
            {
                message = exception.Message;

                if (string.IsNullOrEmpty(message) && (userProfile != null))
                {
                    return (string)userProfile["PersonalSpace"].Value;
                }
                return ("MySpace.aspx?" + SPHttpUtility.UrlKeyValueEncode(c_QueryStringError, message));
            }

            return null;
        }

        
        private void CreateMySite(UserProfile userProfile)
        {

            //SPSecurity.CodeToRunElevated secureCode = null;
            //string strError;
            string strOwnerName = (string)userProfile["PreferredName"].Value;
            string strOwnerEmail = (string)userProfile["WorkEmail"].Value;
            
            string strOwnerLogin = (string)userProfile["AccountName"].Value;
            string strSecondaryLogin = null;

            //create site collection
            SPWebApplication webApplication = SPContext.Current.Site.WebApplication;
            SPSiteCollection siteCollections = webApplication.Sites;

            //SPContext.Current.Web.AllowUnsafeUpdates = true;
           
            //SPSite siteCol = siteCollections.Add("/personal/strOwnerName", strOwnerLogin, strOwnerEmail);
           
            //create root web site from template
            string strWebTemplate = "SPSPERS#0";
            try
            {
                Property propTemplate = userProfile.ProfileManager.Properties.GetPropertyByName(MySpaceTemplateProperty);
                if (propTemplate == null)
                {
                    userProfile.CreatePersonalSite();
                    RedirectToMySpace(userProfile);
                    return;
                }
                else
                {
                    string template = (string)userProfile[MySpaceTemplateProperty].Value;
                    if (string.IsNullOrEmpty(template))
                    {
                        userProfile.CreatePersonalSite();
                        RedirectToMySpace(userProfile);
                        return;
                    }
                    else
                        strWebTemplate = template;
                }
            }
            catch
            {
                //TODO: log that the user will get the default My Site
            }

            
           // string strWebTemplate = "HBSMYSITES#1"; // "BLOG#0"; // "SPSPERS#0";
            string strTitle = "My Space";
            string strDescription = "Personal Space";

            //TODO: create a nicer personal site link from the ownername (do not use Domain if not necessary 

            strOwnerName = strOwnerName.Replace('\\', '_'); 

            //get the /personal/ managed path from the SSP
            string managedFolder = "/" + userProfile.ProfileManager.PersonalSiteInclusion + "/";
            SPSite site = siteCollections.Add(managedFolder+strOwnerName, strTitle, strDescription, 1033, strWebTemplate, strOwnerLogin, strOwnerName, strOwnerEmail, strSecondaryLogin, null, null);
                        

            //update user Profile
            userProfile["PersonalSpace"].Value = site.RootWeb.ServerRelativeUrl;
            userProfile.Commit();

            //TODO: add any code necessary after web site creation

            RedirectToMySpace(userProfile);
           
            
         }


        private void RedirectToMySpace(UserProfile userProfile)
        {
            //Redirect to the Personal Site
            Context.Response.Redirect(userProfile.PersonalUrl.ToString());
        }
 


    }
}
